package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.placeholder.ReplaceContext;
import info.batcloud.fanli.core.placeholder.Placeholder;
import info.batcloud.fanli.core.placeholder.PlaceholderContext;
import info.batcloud.fanli.core.service.PlaceholderService;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class PlaceholderServiceImpl implements PlaceholderService {

    private static Pattern pattern = Pattern.compile("\\{.+\\}?");

    @Override
    public String clean(ReplaceContext replaceContext) {
        String text = replaceContext.getText();
        Matcher matcher = pattern.matcher(text);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String key = matcher.group();
            Placeholder placeholder = PlaceholderContext.getByKey(key);
            if(placeholder != null) {
                matcher.appendReplacement(sb, placeholder.replace(replaceContext));
            } else {
                matcher.appendReplacement(sb, "");
            }

        }
        matcher.appendTail(sb);
        return sb.toString();
    }

}
